package com.zhuliwei.rabbitmq.direct.consumer;

import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.templates.EmailTemplate;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static com.zhuliwei.constants.RabbitConstants.EMAIL_QUEUE2;

/**
 * 注册成功邮件通知消息消费
 *
 * @author 朱力维
 * @time 2024/11/17 18:16
 **/
@Component
@RabbitListener(queues = EMAIL_QUEUE2) //指定监听哪个消息队列
public class EmailMessageConsumer {
    @Resource
    private JavaMailSender sender;
    /**
     * 消息消费
     *
     * @param userMessage 用户信息
     */
    @RabbitHandler
    public void emailToUser(Map<String, Object> userMessage) {
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SystemConstants.EMAIL_SENDER, "小朱");
            helper.setTo(userMessage.get("to").toString());
            helper.setSubject(SystemConstants.BLOG_SUBJECT);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            String time = sdf.format(new Date());
            String text = EmailTemplate.REGISTER_SUCCESS.replace("$EMAIL$", userMessage.get("to").toString()).replace("$NICKNAME$", userMessage.get("nickName").toString()).replace("$DATETIME$", time);
            helper.setText(text, true);
            // 发送填充好的整个html页面
            sender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
